//
//  IGCreatPictureListVC.m
//  jingdongfang
//
//  Created by RKL on 2018/5/9.
//  Copyright © 2018年 BOE-SBG-CTO. All rights reserved.
//

#import "IGCreatPictureListVC.h"
#import "CreatPictureListTagView.h"
#import "PictureListSelectLabelView.h"
#import "IGArtLibraryApi.h"
#import "IGCreatListApi.h"

#define BACKGROUNDCOLOR [UIColor colorWithRed:0/255.0 green:171/255.0 blue:230/255.0 alpha:1.0]
#define BACKTITLECOLOR [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]
#define AutoHeight(height) height*(KSCREENWIDTH/375.0f)

@interface IGCreatPictureListVC ()<CreatPictureListTagViewDelegate,UITextViewDelegate>
{
    BOOL isShow;
    NSString *searchKey;//查询条件
    NSString *pageNumber;//页数，从0开始
    NSString *pageSize;//一页显示列表数
    NSString *queryTime;//查询时间
}
/**
 底部的scrollView
 */
@property (nonatomic , strong) UIScrollView * bottomScrollView;

/**
 画单名称
 */
@property (nonatomic , strong) UITextField * pictureNameTextField;

/**
 标签名称
 */
@property (nonatomic , strong) UITextField * labelNameTextField;

@property (nonatomic , strong) UIButton * selectBtn;

@property (nonatomic , strong) CreatPictureListTagView * tagView;

/**
 数据源
 */
@property (nonatomic , strong) NSMutableArray * dataSourceArray;

/**
 个人简介的输入框
 */
@property (nonatomic , strong) UITextView * personInfoTextView;
/**
 显示字数多少的Label
 */
@property (nonatomic , strong) UILabel * stirngLenghLabel;
/**
 默认字体
 */
@property (nonatomic , strong) UILabel * placeHolder;

/**
 1:选中公开    0：未选中不公开
 */
@property (nonatomic , copy) NSString * isSecrecy;


@property (nonatomic , strong) PictureListSelectLabelView * pictureListSelectView;
@property (nonatomic , strong) IGArtLibraryApi * artLibraryApi;
@property (nonatomic , strong) NSMutableArray * artLibraryArr;

@property (nonatomic, strong) IGCreatListApi * creatListApi;

@end

@implementation IGCreatPictureListVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"新建画单";
    
    UIBarButtonItem * right = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureClick:)];
    [right setTitleTextAttributes:@{NSForegroundColorAttributeName : RGB(0, 171, 230)} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = right;
    
    self.view.backgroundColor = RGB(242, 244, 248);
    
    [self.view addSubview:self.bottomScrollView];
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到view上
    [self.bottomScrollView addGestureRecognizer:tapGestureRecognizer];
    
    
    [self privateBuildUI];
    
    [self dataRequest];

}
#pragma mark - 确定按钮点击事件
- (void)sureClick:(UIBarButtonItem *)sender
{
    NSLog(@" 确定按钮点击事件");
    
    NSLog(@"+++++++++++++++++%s++++++++++++++++++++++++",__func__);
    
    self.creatListApi.drawlistId = @"";
    self.creatListApi.image = @"";
    self.creatListApi.pIds = @"";
    self.creatListApi.title = self.pictureNameTextField.text;
    self.creatListApi.secrecy = self.isSecrecy;
    NSMutableArray * tempArr = [NSMutableArray new];
    for (int i = 0 ; i<self.dataSourceArray.count; i++)
    {
        IGArtDetailLibrary * lib = self.dataSourceArray[i];
        [tempArr addObject:lib.aId];
    }
    self.creatListApi.labels = [tempArr componentsJoinedByString:@","];
    self.creatListApi.content = self.personInfoTextView.text;
    
    if ([self.pictureNameTextField.text isEqualToString:@""] || self.pictureNameTextField.text == nil)
    {
        [self presentMessageTips:@"请填写画单名称"];
    }
    else if (tempArr.count == 0)
    {
        [self presentMessageTips:@"请选择画单标签"];
    }
    
    
    [self.creatListApi startWithDecodeClass:[IGCreatListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error)
    {
        if (responseObject)
        {
            IGCreatListResp * resp = responseObject;
            if ([resp.resHeader.code isEqualToString:@"success"])
            {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }];
    
}


#pragma mark - 创建UI
- (void)privateBuildUI
{
    self.pictureNameTextField = [UITextField quickCreateTextFieldWithFrame:CGRectMake(0, 5, KSCREENWIDTH, 50)
                                                         placeholderString:@"画单名称"
                                                                      font:16
                                                                 textColor:RGB(54, 54, 54)];
    self.pictureNameTextField.backgroundColor = RGB(255, 255, 255);
    UILabel * leftView = [[UILabel alloc] initWithFrame:CGRectMake(0,0,15,54)];
    leftView.backgroundColor = [UIColor clearColor];
    self.pictureNameTextField.leftView = leftView;
    self.pictureNameTextField.leftViewMode = UITextFieldViewModeAlways;
    self.pictureNameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [self.bottomScrollView addSubview:self.pictureNameTextField];
    
    self.isSecrecy = @"0";
    self.selectBtn = ({
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(15, CGRectGetMaxY(self.pictureNameTextField.frame)+5, 30, 30);
//        button.backgroundColor = [UIColor yellowColor];
        [button addTarget:self action:@selector(selectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.selected = NO;
        [button setImage:[UIImage imageNamed:@"picture_unselect"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"picture_select"] forState:UIControlStateSelected];
        button;
    });
    [self.bottomScrollView addSubview:self.selectBtn];
    
    UILabel * labelTitleLabel = ({
        UILabel * label = [[UILabel alloc] init];
        label.frame = CGRectMake(CGRectGetMaxX(self.selectBtn.frame)+10, CGRectGetMaxY(self.pictureNameTextField.frame), 200, 40);
        label.font = [UIFont systemFontOfSize:13];
        label.text = @"设置为私密画单";
        label.textColor = RGB(146, 146, 146);
        label;
    });
    [self.bottomScrollView addSubview:labelTitleLabel];

    UIButton * selectViewBtn = ({
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, CGRectGetMaxY(labelTitleLabel.frame), KSCREENWIDTH, 50);
        [button addTarget:self action:@selector(selectViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor = RGB(255, 255, 255);
        button;
    });
    [self.bottomScrollView addSubview:selectViewBtn];

    UILabel * selectBtnTitleLabel = ({
        UILabel * label = [[UILabel alloc] init];
        label.frame = CGRectMake(15, 0, 200, 50);
        label.font = [UIFont systemFontOfSize:16];
        label.text = @"选择标签";
        label.textColor = RGB(146, 146, 146);
        label;
    });
    [selectViewBtn addSubview:selectBtnTitleLabel];
    
    UIImageView * rightArrowImageView = ({
        UIImageView * imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:@"picture_right_arrow"];
        imageView.frame = CGRectMake(KSCREENWIDTH-23, 36/2, 8, 13);
        imageView;
    });
    [selectViewBtn addSubview:rightArrowImageView];

    UILabel * infoLabel = ({
        UILabel * label = [[UILabel alloc] init];
        label.frame = CGRectMake(15, CGRectGetMaxY(selectViewBtn.frame)+8, KSCREENWIDTH, 15);
        label.font = [UIFont systemFontOfSize:13];
        label.text = @"最多设置3个标签,让其他人更容易发现您的画单";
        label.textColor = RGB(146, 146, 146);
        label;
    });
    [self.bottomScrollView addSubview:infoLabel];

    self.tagView = [[CreatPictureListTagView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(infoLabel.frame), KSCREENWIDTH, 80)];
    self.tagView.dataArray = self.dataSourceArray;
    self.tagView.delegate = self;
    [self.bottomScrollView addSubview:self.tagView];
    [self.tagView reloadeData];
    
    //画单简介
    UIView * personInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tagView.frame), KSCREENWIDTH, 200)];
    personInfoView.backgroundColor = RGB(255, 255, 255);
    [self.bottomScrollView addSubview:personInfoView];
    //画单简介输入框
    self.personInfoTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, KSCREENWIDTH-20, 160)];
    self.personInfoTextView.scrollEnabled = NO;
    self.personInfoTextView.backgroundColor = [UIColor clearColor];
    [self.personInfoTextView setFont: [UIFont systemFontOfSize:16]];
    self.personInfoTextView.textColor = RGB(54, 54, 54);
    self.personInfoTextView.delegate = self;
    [personInfoView addSubview:self.personInfoTextView];
    //默认字体
    self.placeHolder = [UILabel creatLabelWithText:@"画单简介"
                                        FontOfSize:16
                                         textColor:RGB(146, 146, 146)];
    self.placeHolder.frame = CGRectMake(15, 18, AutoHeight(200), 16);
    self.placeHolder.hidden = NO;
    [personInfoView addSubview:self.placeHolder];
    //限制字数
    self.stirngLenghLabel = [UILabel creatLabelWithText:@"0/300"
                                             FontOfSize:14
                                              textColor:RGB(0, 171, 230)];
    self.stirngLenghLabel.frame = CGRectMake(0, 170, KSCREENWIDTH-20, 30);
    self.stirngLenghLabel.textAlignment = NSTextAlignmentRight;
    [personInfoView addSubview:self.stirngLenghLabel];
    
#pragma mark - PictureListSelectLabelView的回调
    @KWeakObj(self)
    self.pictureListSelectView = [[PictureListSelectLabelView alloc] initWithFrame:CGRectMake(KSCREENWIDTH, 0, KSCREENWIDTH, KSCREENHEIGHT)];
    self.pictureListSelectView.filterBlock = ^(NSMutableArray *arr)
    {
        isShow = !isShow;
        [selfWeak hideFilterView];
    };
    self.pictureListSelectView.sureBlock = ^(NSMutableArray * arr)
    {
        isShow = !isShow;
        selfWeak.tagView.dataArray = arr;
        selfWeak.dataSourceArray = arr;
        [selfWeak.tagView reloadeData];
        [selfWeak hideFilterView];
    };
    [[UIApplication sharedApplication].keyWindow addSubview:self.pictureListSelectView];
    isShow = NO;
    
}

#pragma mark - CreatPictureListTagViewDelegate代理（删除选中标签）
- (void) clickRemoveButtonTag:(NSInteger)index
{
    [self.dataSourceArray removeObjectAtIndex:index];
    self.tagView.dataArray = self.dataSourceArray;
    [self.tagView reloadeData];
}

#pragma mark - 选择标签点击事件
- (void) selectViewBtnClick:(UIButton *)sender
{
    NSLog(@"选择标签点击事件");
    [self.personInfoTextView resignFirstResponder];
    [self.pictureNameTextField resignFirstResponder];

    if (_artLibraryArr.count)
    {
        self.pictureListSelectView.dataSource = self.artLibraryArr;
        [self.pictureListSelectView.collectionV reloadData];
        isShow = !isShow;
        if (isShow)
        {
            [self showFilterView];
        }
        else
        {
            [self hideFilterView];
        }
    }
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self hideFilterView];
}
#pragma mark - 显示标签选择
- (void)showFilterView
{
    [UIView animateWithDuration:0.2 animations:^{
        self.pictureListSelectView.frame = CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT);
    }];
}
#pragma mark - 隐藏标签选择
- (void)hideFilterView
{
    [UIView animateWithDuration:0.2 animations:^{
        self.pictureListSelectView.frame = CGRectMake(KSCREENWIDTH, 0, KSCREENWIDTH, KSCREENHEIGHT);
    }];
}
#pragma mark - 标签的请求
- (void)dataRequest
{
    searchKey = @"";
    pageNumber = @"0";
    pageSize = @"10";
    queryTime = @"";
    self.artLibraryApi = [IGArtLibraryApi new];
    self.artLibraryApi.isCreatListLabel = YES;
//    self.api = [IGDatabaseApi new];
//    self.dataArr = [@[] mutableCopy];
    self.artLibraryArr = [@[] mutableCopy];
    @KWeakObj(self)
    [self.artLibraryApi startWithDecodeClass:[IGArtLibraryResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            IGArtLibraryResp *resp = responseObject;
            IGArtLibraryModel *model = resp.data;
            selfWeak.artLibraryArr = [self addSelectStrWithArr:[model.lstClass mutableCopy]];
//            [self dataRequest1];
        }
    }];
}

- (NSMutableArray *)addSelectStrWithArr:(NSMutableArray *)arr
{
    NSMutableArray *temp = [arr mutableCopy];
    for (int i = 0; i < arr.count; i++)
    {
        IGArtLibrary *lib = arr[i];
        IGArtLibrary *libTemp = temp[i];
        for (int j = 0; j < lib.lstSubClass.count; j++)
        {
            IGArtDetailLibrary *dic = libTemp.lstSubClass[j];
            dic.isSelect = @"0";
        }
    }
    return temp;
}

#pragma mark - 选择是否是私密画单按钮的点击事件
- (void)selectBtnClick:(UIButton *)sender
{
    NSLog(@"选择是否是私密画单按钮的点击事件");
    sender.selected = !sender.selected;
    if (sender.selected)
    {
        self.isSecrecy = @"1";
    }
    else
    {
        self.isSecrecy = @"0";
    }
}

#pragma mark - UITextViewDelegate
//正在改变
- (void)textViewDidChange:(UITextView *)textView
{
    if ([textView.text length] == 0)
    {
        [self.placeHolder setHidden:NO];
    }
    else
    {
        [self.placeHolder setHidden:YES];
    }
    
    //实时显示字数
    self.stirngLenghLabel.text = [NSString stringWithFormat:@"%lu/300", (unsigned long)textView.text.length];
    
    //字数限制操作
    if (textView.text.length >= 300)
    {
        textView.text = [textView.text substringToIndex:300];
        self.stirngLenghLabel.text = @"300/300";
    }
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    return YES;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if (textView.text.length > 300)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}
#pragma mark - 懒加载
- (UIScrollView *)bottomScrollView
{
    if (_bottomScrollView == nil)
    {
        _bottomScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, NavigationMagin, KSCREENWIDTH, KSCREENHEIGHT - NavigationMagin)];
        _bottomScrollView.backgroundColor = [UIColor clearColor];
        _bottomScrollView.tag = 999;
    }
    _bottomScrollView.contentSize = CGSizeMake(0, KSCREENHEIGHT - NavigationMagin+100);
    return _bottomScrollView;
}

- (NSMutableArray *)dataSourceArray
{
    if (_dataSourceArray == nil)
    {
        _dataSourceArray = [NSMutableArray new];
    }
    return _dataSourceArray;
}

- (IGCreatListApi *)creatListApi
{
    if (_creatListApi == nil)
    {
        _creatListApi = [IGCreatListApi new];
    }
    return _creatListApi;
}


#pragma mark - 收键盘
-(void)keyboardHide:(UITapGestureRecognizer*)tap
{
    [self.pictureNameTextField resignFirstResponder];
    [self.personInfoTextView resignFirstResponder];
}

@end


















